package com.guodi.map.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.common.utils.ReadFileUtil;
import com.guodi.common.utils.UuidUtil;
import com.guodi.map.constant.MapConst;
import com.guodi.map.entity.MapLayer;
import com.guodi.map.entity.MapLayerField;
import com.guodi.map.mapper.MapLayerFieldMapper;
import com.guodi.map.service.IMapLayerFieldService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

import static com.guodi.map.service.impl.MapDivisionServiceImpl.sendPost2;

/**
 * @描述：图层字段列表 服务类
 * @作者: 代鹏刚
 * @日期: 2019-12-27
 */
@Service
public class MapLayerFieldServiceImpl extends ServiceImpl<MapLayerFieldMapper, MapLayerField> implements IMapLayerFieldService {

    @Resource
    private MapLayerFieldMapper mapLayerFieldMapper;

    @Override
    public List<MapLayerField> listByLayerId(String layerId) {
        LambdaQueryWrapper<MapLayerField> lambdaQueryWrapper = (new QueryWrapper()).lambda();
        lambdaQueryWrapper.eq(MapLayerField::getLayerId,layerId);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public List<MapLayerField> listByLayerIds(List<String> layerIds) {
        LambdaQueryWrapper<MapLayerField> lambdaQueryWrapper = (new QueryWrapper()).lambda();
        lambdaQueryWrapper.in(MapLayerField::getLayerId,layerIds);
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public void saveMapLayerField(List<MapLayerField> mapLayerFields) {
        if(mapLayerFields==null||mapLayerFields.isEmpty()){
            return;
        }
        // 保存前，先删除以前的图层字段数据
        this.deleteByLayerId(mapLayerFields.get(0).getLayerId());

        // 循环保存图层字段信息
        for(MapLayerField mapLayerField : mapLayerFields){
            mapLayerFieldMapper.insert(mapLayerField);
        }
    }

    @Override
    public void deleteByLayerId(String layerId) {
        mapLayerFieldMapper.deleteByLayerId(layerId);
    }

    @Override
    public List<MapLayerField> listByProjectId(String projectId) {
        return mapLayerFieldMapper.listByProjectId(projectId);
    }

    @Override
    public List<MapLayerField> getLayerFieldByParseResult(String layerJsonStr, String layerId, String geometryType) {
        if(StringUtils.isBlank(layerJsonStr)){
            return new ArrayList<>();
        }
        JSONObject layerJson = JSONObject.fromObject(layerJsonStr);
        List<MapLayerField> mapLayerFields = new ArrayList<>();
        if(layerJson.get("fields") != null && !"null".equals(layerJson.getString("fields")) && StringUtils.isNotBlank(layerJson.getString("fields"))){
            // 读取图层字段json数组
            JSONArray fields = layerJson.getJSONArray("fields");
            fillField(fields,layerId,mapLayerFields);
        }
        return mapLayerFields;
    }

    private void fillField(JSONArray fields,String layerId,List<MapLayerField> mapLayerFields){
        for(int i = 0; i < fields.size(); i++){
            JSONObject fieldJson = fields.getJSONObject(i);
            // 新增图层字段
            MapLayerField mapLayerField = new MapLayerField();
            String fieldName = fieldJson.getString("name");
            String fieldType = fieldJson.getString("type");
//                mapLayerField.setFieldType(getFieldType(fieldName,geometryType,fieldType));
            mapLayerField.setFieldType(fieldType);
            mapLayerField.setId(UuidUtil.get32UUID());
            mapLayerField.setFieldName(fieldName);
            mapLayerField.setFieldAlias(fieldJson.getString("alias"));
            mapLayerField.setFieldSize(fieldJson.get("length") == null ? "": fieldJson.get("length").toString());
            mapLayerField.setIsShow(1);
            mapLayerField.setIsLabel(0);
            mapLayerField.setSort(i+1);
            mapLayerField.setLayerId(layerId);
            mapLayerFields.add(mapLayerField);
        }
    }

    @Override
    public List<MapLayerField> getLayerFieldByParseResult(JSONArray parseResult, String layerId, String geometryType) {
        List<MapLayerField> mapLayerFields = new ArrayList<>();
        if(parseResult==null||parseResult.isEmpty()){
            return mapLayerFields;
        }
        fillField(parseResult,layerId,mapLayerFields);
        return mapLayerFields;
    }

    @Override
    public Map<String, List<MapLayerField>> parseLayerFieldByParseResult(String layerUrl, MapLayer mapLayer) {
        String layerId = mapLayer.getId();
        String releaseType = mapLayer.getReleaseType();

        if(!"iserver".equals(releaseType)){
            String layerJsonStr = ReadFileUtil.getStringByUrl(layerUrl+ MapConst.URL_SUFFIX,new HashMap<>());
            JSONObject jsonObject = JSONObject.fromObject(layerJsonStr);
            Object geometryType = jsonObject.get("geometryType");
            List<MapLayerField> layerFields = getLayerFieldByParseResult(layerJsonStr,layerId, geometryType == null ? "" : geometryType.toString());
            Map<String,List<MapLayerField>> result = new HashMap<>();
            Object id = jsonObject.get("id");
            Object nameObj = jsonObject.get("name");
            if(id!=null){
                result.put(id.toString(),layerFields);
            }else{
                result.put(nameObj==null?"":nameObj.toString(),layerFields);
            }
            return result;
        }else {
//            Map<String,List<MapLayerField>> result = new HashMap<>();
//            try {
//                String layerUrlPro = layerUrl;
//                if(layerUrl.lastIndexOf("/datasources") != -1){
//                    layerUrlPro = layerUrl.substring(0,layerUrl.lastIndexOf("/datasources")) + "/featureResults.json";
//                }
//                String layerJsonStr = ReadFileUtil.getStringByUrl(layerUrlPro);
//
//                List<Map> layerJsonList = com.alibaba.fastjson.JSONObject.parseArray(layerJsonStr,Map.class);
//                if(!CollectionUtils.isEmpty(layerJsonList)){
//                    String path = "";
//                    for(Map map : layerJsonList){
//                        if(map.get("path") != null || StringUtils.isNotEmpty(String.valueOf(map.get("path")))){
//                            path = String.valueOf(map.get("path"));
//                            break;
//                        }
//                    }
//                    //拿到path再查字段列表
//                    String fieldJsonStr = ReadFileUtil.getStringByUrl(path);
//                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(fieldJsonStr);
//                    List<Map> datasetInfos = jsonObject.getObject("datasetInfos", ArrayList.class);
//                    for(Map map : datasetInfos){
//                        String name = String.valueOf(map.get("datasetName"));
//                        List<MapLayerField> mapLayerFields = new ArrayList<>();
//                        List<Map> fieldJsons = (List<Map>) map.get("fieldInfos");
//                        int i = 1;
//                        for(Map map1 : fieldJsons){
//                            if(map1.get("name") != null && StringUtils.isNotEmpty(String.valueOf(map1.get("name"))) && !"null".equals(String.valueOf(map1.get("name")))){
//                                MapLayerField mapLayerField = new MapLayerField();
//                                mapLayerField.setFieldName(String.valueOf(map1.get("name")));
//                                mapLayerField.setRemark(String.valueOf(map1.get("caption")));
//                                mapLayerField.setFieldType(String.valueOf(map1.get("type")));
//                                mapLayerField.setIsShow(1);
//                                mapLayerField.setIsLabel(0);
//                                mapLayerField.setLayerId(layerId);
//                                mapLayerField.setSort(i);
//                                i++;
//                                mapLayerFields.add(mapLayerField);
//                            }
//                        }
//                        result.put("result",mapLayerFields);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return result;

            Map<String,List<MapLayerField>> result = new HashMap<>();
            //获取查询的图层名称
            String layerInfoUrl =layerUrl +"/layers.json";
            String jsonStr1  = ReadFileUtil.getJsonByUrl(layerInfoUrl).trim();
            JSONArray jsonArray = JSONArray.fromObject(jsonStr1);
            JSONObject jsonMap = (JSONObject) jsonArray.get(0);
            JSONObject subLayers = jsonMap.getJSONObject("subLayers");
            if(subLayers == null){
                return result;
            }
            try {
                JSONArray layers = subLayers.getJSONArray("layers");

                for(int j = 0; j< layers.size(); j++){
                    if(StringUtils.isNotEmpty(mapLayer.getLayerTable()) && !Objects.equals(mapLayer.getLayerTable(),layers.getJSONObject(j).getString("name"))){
                        continue;
                    }
                    JSONObject datasetInfo = layers.getJSONObject(j).getJSONObject("datasetInfo");
                    //获取图层名称
                    String layerName1 = (String) datasetInfo.get("name");
                    String dataSourceName1 = (String) datasetInfo.get("dataSourceName");
                    String cx_layerName = layerName1 +"@"+dataSourceName1;
                    Map<String, Object> leftBottom = new HashMap<>();
                    leftBottom.put("x", 0);
                    leftBottom.put("y", 0);
                    Map<String, Object> rightTop = new HashMap<>();
                    rightTop.put("x", 100);
                    rightTop.put("y", 100);
                    Map<String, Object> bounds = new HashMap<>();
                    bounds.put("leftBottom", leftBottom);
                    bounds.put("rightTop", rightTop);
                    Map<String, Object> queryParameters = new HashMap<>();
                    ArrayList<Map> queryParams = new ArrayList<>();
                    Map<String, Object> queryParams1 = new HashMap<>();
                    queryParams1.put("attributeFilter", "1: 1");
                    queryParams1.put("name", cx_layerName);
                    queryParams.add(queryParams1);
                    queryParameters.put("queryParams", queryParams);
                    queryParameters.put("startRecord", 0);
                    queryParameters.put("expectCount", 1);
                    queryParameters.put("networkType", "LINE");
                    queryParameters.put("queryOption", "ATTRIBUTE");
                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("queryMode", "SqlQuery");
                    jsonParam.put("bounds", bounds);
                    jsonParam.put("distance", 1);
                    jsonParam.put("queryParameters", queryParameters);
                    jsonParam.put("keywords", "");
                    jsonParam.put("spatialQueryMode", "INTERSECT");
                    String url = layerUrl + "/queryResults.json?returnPostAction=true&getMethodForm=true&returnContent=true";
                    String param = jsonParam.toString();

                    try {
                        //查询获取图层字段值集合
                        String jsonStr = sendPost2(url, param);
                        JSONObject jsonObj = JSONObject.fromObject(jsonStr);

                        JSONArray recordsets = jsonObj.getJSONArray("recordsets");
                        JSONObject recordsetsMap = recordsets.getJSONObject(0);
                        JSONArray fields = recordsetsMap.getJSONArray("fields");
                        JSONArray fieldTypes = recordsetsMap.getJSONArray("fieldTypes");
                        JSONArray fieldCaptions = recordsetsMap.getJSONArray("fieldCaptions");

                        List<MapLayerField> mapLayerFields = new ArrayList<>();
                        for (int i = 0; i < fields.size(); i++) {

                            MapLayerField mapLayerField = new MapLayerField();
                            mapLayerField.setFieldName(String.valueOf(fields.getString(i)));
                            mapLayerField.setRemark(String.valueOf(fieldCaptions.getString(i)));
                            mapLayerField.setFieldType(String.valueOf(fieldTypes.getString(i)));
                            mapLayerField.setIsShow(1);
                            mapLayerField.setIsLabel(0);
                            mapLayerField.setLayerId(layerId);
                            mapLayerField.setSort(i);
                            mapLayerFields.add(mapLayerField);
                            result.put(cx_layerName,mapLayerFields);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }

    private String getFieldType(String fieldName,String  geometryType,String fieldType){
        String result= null;
        if(fieldName.toLowerCase().indexOf("objectid") != -1){
            result = "number";
        }else if ("shape".equals(fieldName.toLowerCase())) {
            result = geometryType;
        }else if(fieldType.toLowerCase().indexOf("integer") != -1 || fieldType.toLowerCase().indexOf("double") != -1){
            result = "number";
        }else if(fieldType.toLowerCase().indexOf("string") != -1){
            result = "varchar";
        }else if(fieldType.toLowerCase().indexOf("date") != -1){
            result = "date";
        }else{
            result = "";
        }
        return result;
    }
}
